package com.fortune.conf;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.api.R;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utils {
    private static final Map<String, String> MIME_TO_EXTENSION_MAP = new HashMap<>();

    static {
        MIME_TO_EXTENSION_MAP.put("image/jpeg", ".jpg");
        MIME_TO_EXTENSION_MAP.put("image/png", ".png");
        MIME_TO_EXTENSION_MAP.put("image/gif", ".gif");
        // 添加其他图片类型的映射
    }

    public static String getImageExtensionFromUrl(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            String contentType = connection.getContentType();
            connection.disconnect();

            return MIME_TO_EXTENSION_MAP.getOrDefault(contentType, ".jpg");
        } catch (IOException e) {
            e.printStackTrace();
            return ".error";
        }
    }
    //获取文件路径
    public static List<String> getAllFiles(File folder) {
        List<String> resultList = new ArrayList<>();
        if (folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        getAllFiles(file);  // 递归调用
                    } else {
                        resultList.add(file.getAbsolutePath());
                    }
                }
            }
        }
        return resultList;
    }
    public static String getUncompressed() {
        return "D:/wwb/1/fc_image/uncompressed/";
    }
    public static String getCompressed() {
        return "D:/wwb/1/fc_image/compressed/";
    }
    public static String getDateDir() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 获取当前日期的年、月、日
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        int day = currentDate.getDayOfMonth();
        String dateDir = year+"/"+month+"/"+day+"/";

        return dateDir;
    }
    /**
     * 根据完整下载资源主要是图片到本地
     * @param urlStr 网址
     */
    public static String downImage(String urlStr){
        String imageResultUrl="";
        String dateDir = getDateDir();

        String substring = urlStr.substring(0, 2);
        if("//".equals(substring)){
            substring = substring.replace("//","http://");
        }
        urlStr = substring + urlStr.substring(2,urlStr.length());
        String dir = getUncompressed() + dateDir;
//        String dir = "D:/wwb/1/fc_image/uncompressed/"+dateDir;
//        String dir = "E:/images/fortune/fc_image/uncompressed/"+dateDir;
        InputStream inputStream = null;
        OutputStream outputStream = null;
//        String[] images = urlStr.split("/");
//        String imageNameAndExtend = images[images.length - 1];

        String imageNameAndExtend = "";
        String imageName = IdUtil.fastSimpleUUID();

        String suffix = getImageExtensionFromUrl(urlStr);
//        String suffix = ".jpg";
//        if(imageNameAndExtend.contains("gif.jpeg")){
//            suffix = ".gif";
//        }
        imageNameAndExtend = imageName + suffix;
        File file = new File(dir + imageNameAndExtend);//创建文件，dir=绝对路径+图片名称后缀

        try {
            File fileTemp = new File(dir);
            if(!fileTemp.exists()){
                fileTemp.mkdirs();
            }
            imageResultUrl = dateDir+imageNameAndExtend;

            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");// 声明请求方式
            urlConnection.setConnectTimeout(6 * 1000);// 设置连接超时
            urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip");
            inputStream = urlConnection.getInputStream();
            outputStream = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int n = 0;
            while((n = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,n);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return imageResultUrl;
    }
}
